package processingdata.airport;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import org.geonames.Toponym;
import org.geonames.ToponymSearchCriteria;
import org.geonames.ToponymSearchResult;
import org.geonames.WebService;

public class AirportTransferData {
	
	public static void main(String[] args)throws Exception
	{
		String inputFileName="project3cs424/GlobalAirportDatabase/airports";
		
		HashMap<String,Double> latitudeMap=new HashMap<String,Double>();
		HashMap<String,Double> longitudeMap=new HashMap<String,Double>();
		
		BufferedReader inputReader=new BufferedReader(new FileReader(new File(inputFileName)));
		BufferedWriter outputWriter=new BufferedWriter(new FileWriter(new File("data/airport.data")));
		while(inputReader.ready())
		{
			String inputLine=inputReader.readLine();
			String inputLineParts[]=inputLine.split(":");
			String airportName=inputLineParts[2];
			String place=inputLineParts[3];
			String country=inputLineParts[4];
			String airportCode1=inputLineParts[0];
			String airportCode2=inputLineParts[1];
			
			double latitude;
			double longitude;
			
			ToponymSearchCriteria searchCriteria=new ToponymSearchCriteria();
			WebService.setUserName("viper11");
			
			
			
			if(latitudeMap.containsKey(place) && longitudeMap.containsKey(place))
				{
					latitude=latitudeMap.get(place);
					longitude=longitudeMap.get(place);
				}
				else
				{
					searchCriteria.setQ(airportName);
					//searchCriteria.setName(city);
					searchCriteria.setCountryCode("US");
					
					
					ToponymSearchResult searchResults=WebService.search(searchCriteria);
					
					
					
					if(searchResults.getTotalResultsCount()==0)
					{
						searchCriteria.setQ(place);
						searchResults=WebService.search(searchCriteria);
						
						if(searchResults.getTotalResultsCount()==0)
						{
							latitude=0;
							latitudeMap.put(place, latitude);
							longitude=0;
							longitudeMap.put(place, longitude);	
						}
						else
						{
							latitude=searchResults.getToponyms().get(0).getLatitude();
							latitudeMap.put(place, latitude);
							longitude=searchResults.getToponyms().get(0).getLongitude();
							longitudeMap.put(place, longitude);
						}
						
					}
					else
					{
						
						latitude=searchResults.getToponyms().get(0).getLatitude();
						latitudeMap.put(place, latitude);
						longitude=searchResults.getToponyms().get(0).getLongitude();
						longitudeMap.put(place, longitude);
					}
					
				}
			
			System.out.println(airportCode1+"\t"+airportCode2+"\t"+airportName+"\t"+place+"\t"+country+"\t"+latitude+"\t"+longitude+"\n");
			outputWriter.write(airportCode1+"\t"+airportCode2+"\t"+airportName+"\t"+place+"\t"+country+"\t"+latitude+"\t"+longitude+"\n");
		}
		
		outputWriter.close();
		
	}

}
